package com.rhzy.wnhc.controller;


import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.rhzy.wnhc.util.AjaxResult;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Api(tags = "图片上传")
@RestController
@RequestMapping("/file")
public class UploadController {
    @PostMapping(value = "/upload")
    public AjaxResult fileUpload(@RequestParam(value = "file") MultipartFile file)  {
        try {
            if (file.isEmpty()) {
                return AjaxResult.addError("上传的文件为空");
            }
            String fileName = file.getOriginalFilename();  // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            //检查是否是图片
            BufferedImage bi = ImageIO.read(file.getInputStream());
            if(bi == null){
                return AjaxResult.addError("上传的文件不是图片");
            }
            String basePath = System.getProperty("user.dir")+File.separator;//项目运行路径
            fileName = UUID.randomUUID() + suffixName; // 新文件名
            Date date = new Date();
            String datePath=new SimpleDateFormat("yyyy/MM/dd/").format(date);

            String filePath=basePath+datePath;// 上传后的路径
            File dest = new File(filePath +fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String filename = "/temp-rainy/"+ datePath+ fileName;
            return AjaxResult.addSuccess(filename,"上传成功！");
        }catch (Exception e){
            e.printStackTrace();
            return  AjaxResult.addError("异常："+e.getMessage());
        }


    }

}
